<?php

/*------------------------------------------------
*
*   Explay Engine Content Management System.
*   Copyright © 2008 Golovdinov Alexander.
*
*-------------------------------------------------
*
*   Official site: wwww.alex-home.spb.ru/explay.html
*   Contact e-mail: golovdinov@gmail.com
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
------------------------------------------------*/


if (!defined ('EXPLAY')) exit;

class commnetsList {
	
	private $data = '';
	private $SITE = array ();
	private $comments = array ();
	private $options_str = '';
	
	public function __contsruct () {
		$this->SITE = CORE::$SITE;
	}
	
	/**
	 * Строит комментарии
	 *
	 * @param string $module латинское название модуля
	 * @param integer $content_id id контента, к которому прикреплены комментарии
	 * @param string $url относительный адрес страницы с контентом
	 * @param string $sort необязательный параметр, может принимать значение равное DESC, что указывает на обратный порядок сортировки комментариев
	 */
	public function build_comments ($module, $content_id, $url, $sort = '') {
		
		$db = MySQL::getInstance ();
		
		$get = $db->query ("SELECT SQL_CACHE comm.*, usr.user_name, usr.user_login FROM ".DB_PEREFIX."_comments AS comm
			LEFT JOIN (SELECT user_id, user_name, user_login FROM ".DB_PEREFIX."_users) AS usr ON usr.user_id = comm.com_uid
			WHERE com_category = '$module' AND com_idi = '$content_id' ORDER BY com_id $sort");
		if ($db->num_rows ($get) > 0) {
				
			Templater::load ('comment.tpl');
			
			while ($com = $db->fetch_array ($get)) {
				$this->comments[$com['com_parent']][] = $com;
			}
			
			$this->show ($this->comments[0], $url);
		}
		
		unset ($get, $this->comments, $db);
	}
	
	/**
	 * Строит список комментариев с дополнительными полями
	 */
	public function build_advanced_articles_comments ($start, $after_url, $order = 'com_rating') {
		
		$db = MySQL::getInstance ();
		
		$query = $db->query ("SELECT SQL_CACHE comment.*, article.art_header, article.art_category, category.cat_header, usr.user_name, usr.user_login  FROM ".DB_PEREFIX."_comments AS comment
			LEFT JOIN (SELECT art_id, art_header, art_category FROM ".DB_PEREFIX."_articles) AS article ON comment.com_idi = article.art_id
			LEFT JOIN (SELECT cat_name, cat_header FROM ".DB_PEREFIX."_art_category) AS category ON category.cat_name = article.art_category
			LEFT JOIN (SELECT user_id, user_name, user_login FROM ".DB_PEREFIX."_users) AS usr ON usr.user_id = comment.com_uid
			WHERE ".$this->options_str." ORDER BY $order DESC LIMIT $start, 30");
		
		$count_ = $db->fetch_array ($db->query ("SELECT COUNT(com_id) AS cnt FROM ".DB_PEREFIX."_comments WHERE ".$this->options_str));
		$count = $count_['cnt'];
		
		if ($count == 0) {
			site_error ('Нет комментариев по заданным условиям!');
			return;
		}
		
		while ($com = $db->fetch_array ($query)) {
			$this->display_advanced_comment ($com);
		}	
				
		if ($count > 3) $this->data .= past_pages($start, 30, $count, '/top/comments/', 'page', $after_url);
		
		unset ($get, $db);

	}
	
	/**
	 * Добаление условия выборки комментариев
	 *
	 * @param string $field имя поля
	 * @param string $value значение поля (необязательный параметр)
	 * @param string $operator оператор между названием поля и значением (необязательный параметр, по-умолчанию "=")
	 * @param string $logic_operator оператор между текущем условием и предыдущим (необязательный параметр, по-умолчанию "AND")
	 */
	public function add_filter ($field, $value = '', $operator = '=', $logic_operator = 'AND') {
		if ($value == '')
			$this->options_str .= ($this->options_str == '')
				? " $field "
				: " $logic_operator $field ";
		else
			$this->options_str .= ($this->options_str == '')
				? " $field $operator '$value' "
				: " $logic_operator $field $operator '$value' ";
	}
	
	/**
	 * Возвращает построенный список комментариев
	 *
	 * @return string
	 */
	public function show_data () {
		
		$this->data = "\r\n<a name=\"comments\" />\r\n<div id=\"comments_div\">\r\n" . $this->data . "\r\n</div>";
		
		return $this->data;
	}
	
	private function show ($arr, $url, $level = 0) {
		if ($level > 300) $level = 300;
		
		foreach ($arr as $comment) {
			$this->display_comment ($comment, $level, $url);
			
			if (isset ($this->comments[$comment['com_id']]))
				$this->show ($this->comments[$comment['com_id']], $url, $level+50);
		}
		
	}
	
	private function display_comment ($com, $level, $url) {
	
		$com['com_author'] = stripslashes($com['com_author']);
		$com['com_text'] = stripslashes($com['com_text']);
		$avatar = '';
		
		if ($com['com_uid'] != '' && $com['com_uid'] != 0) {
			$com['com_name'] = '<a href="/users/'.$com['user_login'].'">'.$com['user_name'].'</a>';
			
			if (file_exists($_SERVER['DOCUMENT_ROOT'].'/images/avatars/'.$com['com_uid'].'.jpg'))
				$avatar = '/images/avatars/'.$com['com_uid'].'.jpg';
			else
				$avatar = '/images/avatars/noavatar.jpg';
			
			$avatar = '<a href="/users/'.$com['user_login'].'" title="'.$com['user_name'].'"><img src="'.$avatar.'" alt="'.$com['user_name'].'" /></a>';
		} else {
			if ($com['com_mail'] != '') {
				$com['com_mail'] = str_replace ('mailto:', '', $com['com_mail']);
				$com['com_name'] = '<a href="mailto:'.$com['com_mail'].'">'.$com['com_name'].'</a>';
			}
		}
		
		if ($com['com_rating'] == 0)
			$com['com_rating'] = '<span class="com_rating_zero">0</span>';
		elseif ($com['com_rating'] > 0)
			$com['com_rating'] = '<span class="com_rating_plus">+'.$com['com_rating'].'</span>';
		else
			$com['com_rating'] = '<span class="com_rating_minus">'.$com['com_rating'].'</span>';
			
		$com['com_rating'] = str_replace ('-', '&minus;', $com['com_rating']);
		
		$com['com_text'] = replace_symbols(n2br($com['com_text']));
		$com['com_text'] = preg_replace ("#(?<![\'|\"])http:\/\/(.+?)(?![\'|\"])[^\s|\)]{0,}#", "<a href=\"\\0\">\\0</a>", $com['com_text']);
		
		if (!isset($_SESSION['lastvisit_'.$com['com_category'].'_'.$com['com_idi']]))
			$new_class = (User::$properties['lastvisit'] < $com['com_date'] && is_registered()) ? 'new' : '';
		else
			$new_class = ($_SESSION['lastvisit_'.$com['com_category'].'_'.$com['com_idi']] < $com['com_date'] && is_registered()) ? 'new' : ''; 
		
		
		$vote = false;
		$com['com_voters'] = explode (',', $com['com_voters']);
		foreach ($com['com_voters'] as $v) if (User::$properties['user_id'] == trim($v)) $vote = true;
		
		Templater::set_var ('id', $com['com_id']);
		
		(is_registered () && my_karma() >= 0 && $vote == false && $com['com_uid'] != User::$properties['user_id'])
			? $com['com_rating'] .= Templater::display_part ('change_rating')
			: $com['com_rating'] .= Templater::display_part ('cant_rating');
		
		if ($com['com_uid'] == 0) $com['com_uid'] = '';
		$com['com_date'] = format_time ($com['com_date']);
		
		Templater::set_var ('comment', $com);
		Templater::set_var ('avatar', $avatar);
		Templater::set_var ('level', $level);
		Templater::set_var ('new_class', $new_class);
		
		$this->data .= Templater::display_part ('comment');
		
	}
	
	private function display_advanced_comment ($com) {
		
		$com['com_text'] = stripslashes($com['com_text']);
		$img = '';
			
		if ($com['com_rating'] == 0)
			$com['com_rating'] = '<span class="com_rating_zero">0</span>';
		elseif ($com['com_rating'] > 0)
			$com['com_rating'] = '<span class="com_rating_plus">+'.$com['com_rating'].'</span>';
		else
			$com['com_rating'] = '<span class="com_rating_minus">'.$com['com_rating'].'</span>';
			
		$com['com_rating'] = str_replace ('-', '&minus;', $com['com_rating']);
		
		if ($com['com_mail'] == '') $com['com_name'] = $com['com_author'];
		else {
			$com['com_mail'] = str_replace ('mailto:', '', $com['com_mail']);
			$name = '<a href="mailto:'.$com['com_mail'].'">'.$com['com_author'].'</a>';
		}
		if ($com['com_uid'] != '' && $com['com_uid'] != 0) {
			$com['com_name'] = '<a href="/users/'.$com['user_login'].'">'.$com['user_name'].'</a>';
			
			$avatar = '<a href="/users/'.$com['user_login'].'"><img src="/avatars/'.$com['com_uid'].'.jpg" title="'.$com['user_name'].'" align="absmiddle" /></a>';
		}
		$com['com_text'] = replace_symbols(n2br($com['com_text']));
		$com['com_text'] = preg_replace ("#(?<![\'|\"])http:\/\/(.+?)(?![\'|\"])[^\s|\)]{0,}#", "<a href=\"\\0\">\\0</a>", $com['com_text']);
		$com['com_date'] = format_time ($com['com_date']);
		
		Templater::set_var ('comment', $com);
		Templater::set_var ('avatar', $avatar);
		
		$this->data .= Templater::display ('advanced_comment.tpl');

	}

	
}